// 不再重复调用函数
if (!(window['page_sourcecode'] == 1)) {
    window['page_sourcecode'] = 1;

    var update_preview_timeout;
    // 下载文件
    {
        //保存html
        function fake_click(obj) {
            var ev = document.createEvent("MouseEvents");
            ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0,
                false, false,
                false, false, 0, null
            );
            obj.dispatchEvent(ev);
        }

        function export_raw(name, data) {
            var urlObject = window.URL || window.webkitURL || window;
            var export_blob = new Blob([data]);
            var save_link = document.createElementNS(
                "http://www.w3.org/1999/xhtml", "a")
            save_link.href = urlObject.createObjectURL(export_blob);
            save_link.download = name;
            fake_click(save_link);
        }
    }

    //下载调用方法
    function page_sourcecode_download() {
        export_raw(`${md5(project_info.pid + ($(`#page_name`).val()))}.html`, editorGetValue());
    }

    // 点击更多按钮时的分享类型
    var share_type = null;

    //文本框大小
    if (browser_info.is_desktop) {
        $("#js_script_textarea_div").css('height', browser_info.height - 92 + 'px')
    }

    function render_function_btn(text_area, id, var_name) {
        $("#" + id).empty()
        html = "";
        for (key in window[var_name]) {
            html +=
                `<button onclick="insert_node_to_part('${text_area}','${id}','${var_name}','${key}')" style="margin-right:5px;margin-top:10px;">${key}</button>`
        }
        $("#" + id).html(html);
    }

    function insert_node_to_part(text_area, id, var_name, key) {
        if (window[var_name][key]) {
            // 如果已选中，则替换
            if (window[text_area].getSelection()) {
                window[text_area].replaceSelection(window[var_name][key] + "\n");
            }
            // 在当前位置插入
            else {
                window[text_area].replaceRange(window[var_name][key] + "\n", {
                    line: window[text_area].getCursor().line,
                    ch: window[text_area].getCursor().ch
                });
            }
        }
    }

    //预置按钮事件
    function codePareBtn(partdata, partid) {
        console.log(JSON.parse(partdata))
    }

    var editor = null;
    require.config({
        paths: { 'vs': 'https://res.dcdev.net/dcdev/v1.0.6/assets/third_part/monaco-editor/vs' },
        'vs/nls': { 'availableLanguages': { '*': 'zh-cn' } }
    });
    require(['vs/editor/editor.main'], function () {
        //创建编辑器
        editor = monaco.editor.create(
            document.getElementById('js_script_textarea_div'),
            {
                value: [''].join('\n'),
                language: 'html',
                theme: 'vs-dark'
            });
        //监听编辑框内容变化
        editor.onDidChangeModelContent((e) => {
            clearTimeout(update_preview_timeout);
            update_preview_timeout = setTimeout(() => {
                $(`#dcdev_html_container`).attr("srcdoc", editor.getValue());
            }, 500);
        });
        //添加右键按钮
        editor.addAction({
            id: "mybutton3",
            contextMenuOrder: 1,
            label: "全屏居中",
            contextMenuGroupId: "mybuttongrp",
            run: (editor) => {
                var replace_text = `<div style="position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);">${get_selected_content()}</div>`;
                replace_selected_content(replace_text);
                //代码
                //text-align: center;<div style="text-align: center;"></div>
                //<div style="display: flex;flex-direction: column;align-items: center;"></div>

            }
        });
        editor.addAction({
            id: "mybutton2",
            contextMenuOrder: 2,
            label: "左对齐",
            contextMenuGroupId: "mybuttongrp",
            run: (editor) => {
                var replace_text = `<div style="text-align: left;display: flex;flex-direction: column;align-items: flex-start;">${get_selected_content()}</div>`;
                replace_selected_content(replace_text);
                //代码
                //<div style="display: flex;flex-direction: column;align-items: flex-start;"></div>
                //<div style="text-align: left;"></div>
            }
        });
        editor.addAction({
            id: "mybutton3",
            contextMenuOrder: 3,
            label: "居中",
            contextMenuGroupId: "mybuttongrp",
            run: (editor) => {
                var replace_text = `<div style="text-align: center;display: flex;flex-direction: column;align-items: center;">${get_selected_content()}</div>`;
                debugger;
                replace_selected_content(replace_text);
                //代码
                //text-align: center;<div style="text-align: center;"></div>
                //<div style="display: flex;flex-direction: column;align-items: center;"></div>

            }
        });

        editor.addAction({
            id: "mybutton4",
            contextMenuOrder: 4,
            label: "右对齐",
            contextMenuGroupId: "mybuttongrp",
            run: (editor) => {
                var replace_text = `<div style="text-align: right;display: flex;flex-direction: column;align-items: flex-end;">${get_selected_content()}</div>`;
                replace_selected_content(replace_text);
                //代码
                //text-align: center;<div style="text-align: center;"></div>
                //<div style="display: flex;flex-direction: column;align-items: flex-end;"></div>
            }
        });
        //监听点击事件并获取点击坐标
        editor.onMouseDown(e => {
            window.startLineNumber_temp = e.target.position.lineNumber;//获取起始行
            window.startColumn_temp = e.target.position.column;//获取起始列
            //console.log("起始地址："+startLineNumber,startColumn)
        })
        //编辑器鼠标指针选择种事件
        editor.onDidChangeCursorPosition(e => {
            window.endLineNumber = e.position.lineNumber;//获取结束行
            window.endColumn = e.position.column;//获取结束列
            //这里知道结束选中了，把起始行列的临时区的值放到正式区
            //这样解决了，因为右键菜单，导致起始行列错乱的问题
            window.startLineNumber = window.startLineNumber_temp
            window.startColumn = window.startColumn_temp
        })
    });
    //为选中区域加div
    function add_div() {
        var select = get_select_content();
        var content = editor.getValue();
        content = content.replace(select, "<div>\n\t" + select + "\n</div>")
        console.log(content)
        editor.setValue(content);
    }

    //删除选中内容(未做)
    function editorUndo() {
        editor.getModel().undo();
    }
    function editorRedo() {
        editor.getModel().redo();
    }
    function editorGetValue() {
        return editor.getValue()
    }
    function editorSetValue(content) {
        editor.setValue(content);
    }

    // 每个tab下的功能按钮统一处理函数
    function click_config_function_button(element, editor) {
        // 执行更多功能
        function exec_config_function(component, func) { }
        // 获得是属于哪个类别的代码的id
        id = element.parentElement.className;
        func = null;
        switch (id) {
            case "body_textarea_div":
                if (element.className.indexOf("undo") > 0) {
                    editorUndo()
                } else if (element.className.indexOf("redo") > 0) {
                    editorRedo()
                }
                break;
            default:
                break;
        }
    }
    // 以现输入代码渲染html
    function render_html() {
        // 获取当前输入代码
        _js_script_ = _code_mirror_editor_js_script_.getValue();

        // 组织html数据
        data = {
            header: _header_,
            style: _style_,
            body: _body_,
            js_file: _js_file_,
            js_script: _js_script_,
        }
        // 预览html相关赋值操作
        preview_html("preview_iframe", data);
    }
    ui_class.hide_loading();
    var layout_path = localStorage[`layout_${md5(project_info.pid + ($(`#page_name`).val() ? $(`#page_name`).val() : ""))}`];
    $.ajax({
        url: `dcdev/v1.0.6/func/${layout_path}`,//json文件位置
        type: "get",//请求方式为get
        success: function (res) {
            _code_mirror_editor_js_script_.setValue(res)
        }
    })

    function insert_to_code_editor(config, content, is_undo) {
        debugger;
        // editor.getModel().undo();
        editor.focus()
        var selection = editor.getSelection()
        var range = new monaco.Range(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn)
        var id = { major: 1, minor: 1 }
        var op = { identifier: id, range: range, text: content, forceMoveMarkers: true }
        editor.executeEdits('js_script_textarea_div', [op])
    }

    // 获取当前选中内容
    function get_selected_content() {
        return editor.getModel().getValueInRange(editor.getSelection())
    }

    // 替换当前选中内容（没有选中内容则插入到当前位置）
    function replace_selected_content(text) {
        let selection = this.editor.getSelection()
        let range = new monaco.Range(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn)
        let id = { major: 1, minor: 1 }
        let op = { identifier: id, range: range, text: text, forceMoveMarkers: true }
        this.editor.executeEdits(this.root, [op])
        this.editor.focus()
    }

    // 删除当前选中内容
    function remove_selected_content() {
        let selection = this.editor.getSelection()
        let range = new monaco.Range(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn)
        let id = { major: 1, minor: 1 }
        let op = { identifier: id, range: range, text: "", forceMoveMarkers: true }
        this.editor.executeEdits(this.root, [op])
        this.editor.focus()
    }
}